from django.urls import get_urlconf, get_resolver, URLPattern, URLResolver
from system.models import Url

from django.core.management.base import BaseCommand


def get_all_url(resolver=None, pre='/', exclude: list = None):
    """生成 全url 排除部分url"""
    if resolver is None:
        resolver = get_resolver(get_urlconf())

    for r in resolver.url_patterns:
        url = pre + str(r.pattern)

        if url in exclude:
            continue
        if isinstance(r, URLPattern):
            yield url
        if isinstance(r, URLResolver):
            yield from get_all_url(r, url, exclude)


def main():
    queryset = Url.objects.all()
    if queryset.exists():
        queryset.delete()
    data = []
    for url in get_all_url(exclude=['/token/access/', '/token/refresh/']):
        # 特殊处理
        if 'pk' not in url:
            url = url.replace('^', '')
            url = url.replace('$', '')
        data.append(Url(name=url))

    Url.objects.bulk_create(data)


class Command(BaseCommand):
    help = '重置 url'

    def handle(self, *args, **options):
        self.stdout.write('开始')
        main()
        self.stdout.write('url 重置成功 请查看表 system_url')
